package mobi.richaze.llbag.infrastructure.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import mobi.richaze.llbag.domain.shared.BaseRepository;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Functionality common to all Hibernate repositories.
 * 此接口实现本系统实体的CRUD操作
 */
public abstract class HibernateRepository<E> extends HibernateDaoSupport
		implements BaseRepository<E> {

	private Class<E> entityClass;
	private static final Logger log = LoggerFactory
			.getLogger(HibernateRepository.class);

	@SuppressWarnings("unchecked")
	public HibernateRepository() {
		entityClass = (Class<E>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@Autowired
	public void setSessionFactorys(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	public E getEntity(Serializable id) {
		log.debug("getting Entity instance with id: " + id);
		E entity = getHibernateTemplate().get(entityClass, id);
		return entity;
	}

	public List<E> getAllEntity() {
		return null;

	}

	public Serializable saveEntity(E entity) {
		log.debug("saving Entity instance");
		Serializable id = null;
		try {
			id = getHibernateTemplate().save(entity);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return id;
	}

	public void removeEntity(Serializable id) {
		log.debug("deleting Entity instance");
		E entity = getHibernateTemplate().get(entityClass, id);
		if (entity != null) {
			try {
				getHibernateTemplate().delete(entity);
				log.debug("delete successful");
			} catch (RuntimeException re) {
				log.error("delete failed", re);
				throw re;
			}
		}
	}

	public void updateEntity(E entity) {
		log.debug("updating Entity instance");
		try {
			getHibernateTemplate().update(entity);
			log.debug("updating successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
}
